<template>
  <div class="p-2">
    <nimbus-search :columns="searchColumns" v-model="queryParams" @query="handleQuery"></nimbus-search>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['base:material:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['base:material:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['base:material:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['base:material:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="materialList" @selection-change="handleSelectionChange" height="calc(100vh - 400px)">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="物料ID" align="center" prop="materialId" v-if="false" />
        <el-table-column label="物料编码" align="center" prop="materialCode" />
        <el-table-column label="物料描述" align="center" prop="materialDesc" />
        <el-table-column label="物料类型" align="center" prop="materialType" />
        <el-table-column label="产业编码" align="center" prop="industryCode">
          <template #default="scope">
            <dict-tag :options="base_industry" :value="scope.row.industryCode" />
          </template>
        </el-table-column>
        <el-table-column label="产业名称" align="center" prop="industryName" />
        <el-table-column label="工厂编码" align="center" prop="plantCode" />
        <el-table-column label="长度" align="center" prop="length" />
        <el-table-column label="宽度" align="center" prop="width" />
        <el-table-column label="高度" align="center" prop="height" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['base:material:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['base:material:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改物料对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="materialFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料描述" prop="materialDesc">
          <el-input v-model="form.materialDesc" placeholder="请输入物料描述" />
        </el-form-item>
        <el-form-item label="产业编码" prop="industryCode">
          <el-select v-model="form.industryCode" placeholder="请选择产业编码">
            <el-option v-for="dict in base_industry" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产业名称" prop="industryName">
          <el-input v-model="form.industryName" placeholder="请输入产业名称" />
        </el-form-item>
        <el-form-item label="工厂编码" prop="plantCode">
          <el-input v-model="form.plantCode" placeholder="请输入工厂编码" />
        </el-form-item>
        <el-form-item label="长度" prop="length">
          <el-input v-model="form.length" placeholder="请输入长度" />
        </el-form-item>
        <el-form-item label="宽度" prop="width">
          <el-input v-model="form.width" placeholder="请输入宽度" />
        </el-form-item>
        <el-form-item label="高度" prop="height">
          <el-input v-model="form.height" placeholder="请输入高度" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Material" lang="ts">
import { listPlant } from '@/api/base/plant';
import { pageMaterial, getMaterial, delMaterial, addMaterial, updateMaterial } from '@/api/base/material';
import { MaterialVO, MaterialQuery, MaterialForm } from '@/api/base/material/types';
import { PlantVO } from '@/api/base/plant/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { base_industry, sys_normal_disable } = toRefs<any>(proxy?.useDict('base_industry', 'sys_normal_disable'));

const materialList = ref<MaterialVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const plantList = ref<PlantVO[]>([]);

const searchColumns = computed<TableColumn[]>(() => [
  {
    label: '物料编码',
    prop: 'materialCode',
    type: 'input'
  },
  {
    label: '物料描述',
    prop: 'materialDesc',
    type: 'input'
  },
  {
    label: '物料类型',
    prop: 'materialType',
    type: 'select',
    options: [
      {
        label: '普通物料',
        value: '1'
      },
      {
        label: '特殊物料',
        value: '2'
      }
    ]
  },
  {
    label: '产业编码',
    prop: 'industryCode',
    type: 'select',
    options: base_industry.value
  },
  {
    label: '工厂编码',
    prop: 'plantCode',
    type: 'select',
    options: plantList.value
  },
  {
    label: '状态',
    prop: 'status',
    type: 'select',
    options: sys_normal_disable.value
  }
]);

const queryParams1 = reactive<MaterialQuery>({
  pageNum: 1,
  pageSize: 10,
  materialCode: undefined,
  materialDesc: undefined,
  materialType: undefined,
  industryCode: undefined,
  plantCode: undefined,
  status: undefined,
  params: {}
});

const materialFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MaterialForm = {
  materialId: undefined,
  materialCode: undefined,
  materialDesc: undefined,
  materialType: undefined,
  industryCode: undefined,
  industryName: undefined,
  plantCode: undefined,
  length: undefined,
  width: undefined,
  height: undefined,
  status: '0'
};
const data = reactive<PageData<MaterialForm, MaterialQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    materialCode: undefined,
    materialDesc: undefined,
    materialType: undefined,
    industryCode: undefined,
    plantCode: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    materialCode: [{ required: true, message: '物料编码不能为空', trigger: 'blur' }],
    materialDesc: [{ required: true, message: '物料描述不能为空', trigger: 'blur' }],
    materialType: [{ required: true, message: '物料类型不能为空', trigger: 'change' }],
    industryCode: [{ required: true, message: '产业编码不能为空', trigger: 'change' }],
    plantCode: [{ required: true, message: '工厂编码不能为空', trigger: 'blur' }],
    length: [{ required: true, message: '长度不能为空', trigger: 'blur' }],
    width: [{ required: true, message: '宽度不能为空', trigger: 'blur' }],
    height: [{ required: true, message: '高度不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询库位信息列表 */
const getPlantList = async () => {
  const res = await listPlant();
  plantList.value = res.data.map((item) => {
    item.label = item.plantCode + ' - ' + item.plantName;
    item.value = item.plantCode;
    return item;
  });
};

/** 查询物料列表 */
const getList = async () => {
  loading.value = true;
  console.log('queryParams: ', queryParams.value);
  const res = await pageMaterial(queryParams.value);
  materialList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  materialFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = (params: any) => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MaterialVO[]) => {
  ids.value = selection.map((item) => item.materialId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加物料';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MaterialVO) => {
  reset();
  const _materialId = row?.materialId || ids.value[0];
  const res = await getMaterial(_materialId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改物料';
};

/** 提交按钮 */
const submitForm = () => {
  materialFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.materialId) {
        await updateMaterial(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMaterial(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: MaterialVO) => {
  const _materialIds = row?.materialId || ids.value;
  await proxy?.$modal.confirm('是否确认删除物料编号为"' + _materialIds + '"的数据项？').finally(() => (loading.value = false));
  await delMaterial(_materialIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'base/material/export',
    {
      ...queryParams.value
    },
    `material_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  getPlantList();
});
</script>
